////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.os.Handler;
import android.os.Process;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import cc.telecomdigital.tdstock.CustomizeDialogDualMax;
import cc.telecomdigital.tdstock.CustomizeDialogDualMax.IOnDialogButtonClick;
import cc.telecomdigital.tdstock.BaseAsyncTask;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.ExceptionHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.ActivityGroup_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.LS_Authentication.LS_Authentication_Result;
import cc.telecomdigital.tdstock.Services.LS_ClientParamMemory;
import cc.telecomdigital.tdstock.Services.LS_UserClient.CONNECTION_STATUS;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Authentication_Report;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_ConnectionListener;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.Services.LS_UserClient.LS_UserClient_Authentication_Result;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.foreignexchange.ForeignExchangeActivity;
import cc.telecomdigital.tdstock.activity.groups.index.IndexActivity;
import cc.telecomdigital.tdstock.activity.groups.index.IndexCOPListActivity;
import cc.telecomdigital.tdstock.activity.groups.monitor.PortfolioActivity;
import cc.telecomdigital.tdstock.activity.groups.more.MetalActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.CurrentStockInfoActivity;

import com.lightstreamer.ls_client.UpdateInfo;

/**
 * base class on Activity, share basic views,function
 * @author haibo
 *
 */
public abstract class BaseActivity extends /*Activity*/ ActivityGroup_Framework implements ILS_UserClient_Response //,ILS_UserClient_ConnectionListener
{
	protected static final String				ACTION_INSTALL_SHORTCUT			= "com.android.launcher.action.INSTALL_SHORTCUT";
	protected static final String				EXTRA_SHORTCUT_DUPLICATE			= "duplicate";
	protected final static String				TAG							= BaseActivity.class
																			.getSimpleName();
	protected final static String				ACTIVITY_PACKAGE				= "activity.";
	
	protected final static int				RESTART_LIGHTSTREAMER_DELAY_TIME	= 2 * 1000;								//wait for 3 seconds to restart  light  streamer when there's some exception happened.
	protected final static double				REQUEST_FREQUENCY_TIME			= 1.0d;									//1 second
	protected final static double				REQUEST_FREQUENCY_TIME_FOR_DELAY	= 1.0 * 15 * 60d;							//15  minutes;
	protected final static int				BUFFERED_READER_SIZE			= 12 * 1024;								//12K;

	protected boolean						_isInBackground				= false;
	protected boolean						_isConnected					= false;									// the mark of the connection status;
	protected static boolean					_isExceptionHappend				= false;									//the mark of the connection  state
	protected boolean						_isFirstLink					= true;
	protected WindowManager.LayoutParams	mWindowParams;
	public static WindowManager				mWindowManager;
	
	public static ViewGroup					_iconTip;
	private ViewGroup						_iconContent;
	
	//public ViewGroup						_streamerTimeoutLabel;

	protected static Display					_display;

	protected static SharedPreferences			_prefs;

	
	protected static String					_progressTitle_res				= null;
	protected static String					_progressContent_res			= null;
	protected static String					_progressLinking_res			= null;

	protected static String					_menu_exit_app_res				= null;
	protected static String					_menu_gen_launcher_res			= null;

//	private static String					SUCCESS_CODE					= "0";
	public static final int					EXIT_APP						= Menu.FIRST + 1;
	public static final int					CREATE_LAUNCHER				= Menu.FIRST;
	public static final int                 COPY=Menu.FIRST+2;
	public static final int	         BACK= Menu.FIRST + 3;
	public static final int                  FORWARDING=Menu.FIRST +4;

/*	protected LSClient						_myClient;
	public ArrayList<SubscribedTableKey>		_subscrRefs					= new ArrayList<SubscribedTableKey>();*/
	protected Handler						_messageHandler				= new Handler();

	public static Class<? extends Activity>  _currActivityClass;
//	public static Class<? extends BaseActivity>	_currentActivityClass;
//	public static Activity					_parentActivity;

	protected static Toast					_toast;
	protected static CustomizeDialog			_retryDialog;
	//	 protected static ProgressDialog  _progressDialog;

	protected boolean						_isShowingStreamerTimeoutLabel;
	
	private ConditionVariable	conditionVariableForConnection;		
	
	
	protected  int  _id_Networking_Disconnected_Tips = 60;
	
	public static  BaseActivity   INSTANCE_FOR_LIGHTSTREAMER_ONLY = null;
	private static final  Class<?>[]  LIGHTSTREAMER_ACTIVITY_CLASS = {
		ForeignExchangeActivity.class, 
		CurrentStockInfoActivity.class, 
		IndexActivity.class,
		IndexCOPListActivity.class,
		MetalActivity.class/*,
		PortfolioActivity.class*/};
	
	
	//protected boolean subscribeOnResumeOpt = false;   //do it myself

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		ExceptionHandler.register(this);
		_display = ((WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay();

		_prefs = getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING,
				Context.MODE_PRIVATE);

		// _savedInstanceState   =  savedInstanceState == null ? getIntent().getExtras()  : savedInstanceState;
		_progressTitle_res = getResources().getString(
				R.string.loading_indicator);
		_progressContent_res = getResources().getString(
				R.string.loading_mesgr);
		_progressLinking_res = getResources().getString(
				R.string.linking_mesgr);

		_menu_exit_app_res = getResources().getString(R.string.app_exit);
		_menu_gen_launcher_res = getResources().getString(
				R.string.app_launcher);

		TDStockLog.d(TAG, "create a new instance: "
				+ BaseActivity.this.getClass().getSimpleName());
		
		subscribeOnResumeOpt = false;
		
	}
	  /**
	   * 
	   * @return  current page is lightstreamer activity or not
	   */
	  public      static  boolean isLightStreamerActivity( Class theClass) {
		  boolean result = false;
		  for(Class tmpClass : LIGHTSTREAMER_ACTIVITY_CLASS ) 
		  {
			  if (tmpClass.getSimpleName().equals(theClass.getSimpleName()))
			  {
				  result = true;
				  break;
			  }
		  }
		  return result;
	  }
	
	public void connectLightStreamerExt(Context context) 
	{
		
		if(appHost.LSClient_IsConnected())
		{
			startupLightStreamerTimeoutThread();
			onConnectionEstablished();
			return;   //connected to the server already!
		}
		else
		{
			new ConnectLightStreamerEx(context).execute();
		}
		
	}
	
	/** modify by zor(ouyangzhihui) -start */
	public void startAnimat(String text)
	{
		mWindowManager = (WindowManager) BaseActivity.this.getMyOwnContext()
				.getSystemService(Context.WINDOW_SERVICE);

		setBitmapImageDesc(text);
		setBitmapImage(text);
	}

	protected WindowManager.LayoutParams getParams()
	{
		final WindowManager.LayoutParams wl = new WindowManager.LayoutParams();

		wl.x = 0;
		wl.y = 0;

		wl.height = WindowManager.LayoutParams.WRAP_CONTENT;
		wl.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wl.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
				| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
		wl.format = PixelFormat.TRANSLUCENT;
		wl.windowAnimations = 0;
		return wl;
	}

	private void setBitmapImage(String itemCode)
	{
		try
		{
			if (itemCode.indexOf(" ") != -1)
			{
				itemCode = itemCode.substring(itemCode.indexOf(" ") + 1,
						itemCode.length());
			}
			String text = itemCode.length() >= 5 ? itemCode.substring(0, 5)
					: itemCode;
			if (_iconTip == null)
			{
				_iconTip = (ViewGroup) LayoutInflater.from(this).inflate(
						R.layout.label_tip_icon, null);
			}
			TextView iv = (TextView) _iconTip.findViewById(R.id.tip_code);
			iv.setText(text);
			if (text.length() == 1)
			{
				iv.setBackgroundResource(R.drawable.monitor_cicle);
			}
			else
			{
				iv.setBackgroundResource(R.drawable.monitor_rectangle);
			}

			final WindowManager.LayoutParams wl = getParams();

			int width = _display.getWidth();
			int height = _display.getHeight();
			int iw = iv.getWidth();
			int ih = iv.getHeight();
			int w = (width / 2) / 5 / 2;
			int h = (height / 2) / 8 / 2;

			int wc = w / 2 - iw / 2;
			int hc = h / 2 - ih / 2;

			wl.x = -(width / 20) * 3 + wc;
			wl.y = height / 2 - height / 16 - hc + 3;

			mWindowManager.addView(_iconTip, wl);

		}
		catch (Exception e)
		{
		}
	}

	private void setBitmapImageDesc(String itemCode)
	{
		try
		{
			if (_iconContent == null)
			{
				_iconContent = (ViewGroup) LayoutInflater.from(this)
						.inflate(R.layout.label_tip_content, null);
			}
			TextView iv = (TextView) _iconContent
					.findViewById(R.id.tip_code);
			iv.setText(itemCode);

			final WindowManager.LayoutParams wl = getParams();
			wl.gravity = Gravity.TOP;
			wl.alpha = 0.3f;
			wl.x = -(_display.getWidth() / 2 - iv.getWidth() / 2 - 10);
			wl.y = 80;

			mWindowManager.addView(_iconContent, wl);

			final Runnable runnable = new Runnable()
			{
				public void run()
				{
					try
					{
						wl.y += 80;
						if (_iconContent != null
								&& mWindowManager != null)
							mWindowManager.updateViewLayout(
									_iconContent, wl);
					}
					catch (Exception e)
					{
					}
				}
			};

			new Thread()
			{
				long	lastUpdate	= System.currentTimeMillis();

				public void run()
				{
					while (wl.y < _display.getHeight() - 60)
					{
						if (System.currentTimeMillis() - lastUpdate >= 100)
						{
							lastUpdate = System.currentTimeMillis();
							_messageHandler.post(runnable);
						}
					}
					if (_iconContent != null && mWindowManager != null)
						mWindowManager.removeView(_iconContent);
				}
			}.start();
		}
		catch (Exception e)
		{
		}
	}
	/** modify by zor(ouyangzhihui) -end */

	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		resetMinHeightOnWorkCenter();
	}

	protected void resetMinHeightOnWorkCenter()
	{
		ViewGroup workCenter = (ViewGroup) findViewById(R.id.workcenter);
		if (workCenter == null)
		{
			return;
		}
		else
		{
			workCenter
					.setMinimumHeight(_display.getHeight() > 800 ? _display
							.getHeight() - 150
							: 600);
		}

	}

	protected void onSessionStarted(boolean arg0)
	{

	}

	protected synchronized void onConnectionEstablished()
	{
	}

	protected String getUser()
	{
		return ((ITDLApplication) getApplicationContext())
				.getUserName(CommonDefn.SYSTEM_TRIAL_ACCOUNT_USER);
	}

	protected String getPwd()
	{
		return ((ITDLApplication) getApplicationContext())
				.getPwd(CommonDefn.SYSTEM_TRIAL_ACCOUNT_PWD);
	}

//	protected String getRsiTerm()
//	{
//		return ((ITDLApplication) getApplicationContext()).getPreferRsiTerm();
//	}
//
//	protected int getUserId()
//	{
//		return ((ITDLApplication) getApplicationContext()).getUserId(-1);
//	}

	/**
	 * default value: empty string
	 *  a not empty string is a useful activation code
	 * @return
	 */
	protected String getActivationCode()
	{
		String result = _prefs.getString(
				CommonDefn.PREFERENCE_TRIAL_ACTIVE_CODE, "");
		return result;
	}

//	protected String getDeviceId()
//	{
//		return ((ITDLApplication) getApplicationContext()).getDeviceId();
//	}
//
//	protected String getAdapterSet()
//	{
//		return ((ITDLApplication) getApplicationContext()).getAdapterSet();
//	}

	protected String getWebServer()
	{
		return LS_ClientParamMemory.GetWebServerInfo();
//		return ((ITDLApplication) getApplicationContext()).getWebServer();
	}

//	protected String getLightStreamer()
//	{
//		return ((ITDLApplication) getApplicationContext()).getLightStreamer();
//	}

//	protected double getRequestFrequency()
//	{
//		return CommonDefn.ADAPTER_SET_FOR_FREE.equals(getAdapterSet()) ? REQUEST_FREQUENCY_TIME_FOR_DELAY
//				: REQUEST_FREQUENCY_TIME;
//	}
//
//	protected String getSessionToken()
//	{
//		return ((ITDLApplication) getApplicationContext()).getSessionToken();
//	}
//
//	protected String getSessionAccount()
//	{
//		return ((ITDLApplication) getApplicationContext())
//				.getSessionAccount();
//	}

	protected boolean isAuthComingFromActivationCode()
	{
		String activationCode = getActivationCode();
		//		 boolean result = (activationCode != null && activationCode.length() >=1 && 	((ITDLApplication)getApplicationContext()).getEnvironment() != CommonDefn.Environment.Production) ;

		boolean result = (activationCode != null
				&& activationCode.length() >= 1 && ((ITDLApplication) getApplicationContext())
				.isAuthComeFromActivationCode());
		return result;
	}

	/*@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		Log.d(TAG, "home -> onKeyDown");
		if(KeyEvent.KEYCODE_HOME == keyCode)
		{
			Log.d(TAG, "home -> onKeyDown="+keyCode);
			android.os.Process.killProcess(android.os.Process.myPid());
		}
	     return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onAttachedToWindow()
	{
		super.onAttachedToWindow();
		this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
		Log.d(TAG, "home ->");
	}*/
	
	
	
	@Override
	public void onBackPressed()
	{
		syncBackPressed();
	}

//	@Override
//	protected void onStop()
//	{
//		super.onStop();
//		Log.d(TAG, "onStop->");
//	}

	protected void syncBackPressed()
	{
		// TODO Auto-generated method stub
		Object returnBtn = findViewById(R.id.more_returnbtn);
		if (returnBtn != null && returnBtn instanceof Button
				&& ((Button) returnBtn).getVisibility() == View.VISIBLE)
		{
			if (((Button) returnBtn).performClick())
			{
				return;
			}
		}
		TDStockLog.d(TAG, "activity is: " + BaseActivity.this.getLocalClassName());

		if ((ACTIVITY_PACKAGE + CurrentStockInfoActivity.class
				.getSimpleName()).equals(BaseActivity.this
				.getLocalClassName()))
		{
			handleExitApplication();
			return;
		}

		/*if(_toolbutton_stock != null) {
			if(_toolbutton_stock.performClick()) {
				return;
			}
		}*/
		StockGroup.forceToGoToRelatingTab(); //hit cancel key when enter stockinfo screen as the default action
		//super.onBackPressed();
	}

	protected synchronized void handleLightStreamerException(Exception e)
	{
		//e.printStackTrace();
		if (_isInBackground)
		{
			return;
		}
		//Toast.makeText(BaseActivity.this, R.string.light_streamer_error, Toast.LENGTH_SHORT).show();
		TDStockLog.d(TAG, e.getMessage() == null ? "unkonw exception caught!" : e
				.getMessage());
		final Runnable myUpdateResults = new Runnable()
		{
			public void run()
			{
				try
				{
					//Thread.sleep(RESTART_LIGHTSTREAMER_DELAY_TIME);
					//connectLightStreamer(); //restart it self
					TDStockLog.d(TAG, "cameFromTag=retry connect ls");
					new ConnectLightStreamerEx(getMyOwnContext()).execute();
				}
				catch (Exception e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		};

		new Thread()
		{
			public void run()
			{
				_messageHandler.postDelayed(myUpdateResults,
						RESTART_LIGHTSTREAMER_DELAY_TIME);
				//	_messageHandler.post(myUpdateResults);
			}
		}.start();
	}

	protected synchronized void handleLightStreamerException(Exception e,
			final Runnable currentJob)
	{
		if (this._isInBackground)
		{
			return;
		}
		//Toast.makeText(BaseActivity.this, R.string.light_streamer_error, Toast.LENGTH_SHORT).show();
		TDStockLog.d(TAG, e.getMessage() == null ? "unkonw exception caught!" : e
				.getMessage());
		final Runnable myUpdateResults = new Runnable()
		{
			public void run()
			{
				try
				{
					Thread.sleep(RESTART_LIGHTSTREAMER_DELAY_TIME);
					currentJob.run();
				}
				catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		};

		new Thread()
		{
			public void run()
			{
				_messageHandler.post(myUpdateResults);
			}
		}.start();
	}

	protected synchronized void handleExitApplication()
	{
		new AlertDialog.Builder(/*this*/this.getParent() == null ? this
				: this.getParent()).setTitle(
				getResources().getString(R.string.info)).setMessage(
				getResources().getString(R.string.application_exit_tips))
				.setIcon(
						getResources().getDrawable(
								R.drawable.help_menu_icon))
				.setPositiveButton(getResources().getString(R.string.ok),
						new DialogInterface.OnClickListener()
						{
							public void onClick(
									DialogInterface dialoginterface,
									int i)
							{
								((ITDLApplication) getApplicationContext())
										.setExitApp(true);
								exitApp();
							}
						}).setNegativeButton(
						getResources().getString(R.string.cancel),
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog,
									int whichButton)
							{

							}
						}).show();

	}

	protected synchronized void unexpectedExitApplication()
	{
		try
		{
			new AlertDialog.Builder(
					/*this*//*BaseActivity.this.getParent()*/getParent() == null ? this : this.getParent())
					.setTitle(getResources().getString(R.string.info))
					.setMessage(
							getResources().getString(
									R.string.unexpected_exit_app_tips))
					.setIcon(
							getResources().getDrawable(
									R.drawable.help_menu_icon))
					.setPositiveButton(
							getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener()
							{
								public void onClick(
										DialogInterface dialoginterface,
										int i)
								{
									((ITDLApplication) getApplicationContext())
											.setExitApp(true);
									exitApp();
								}
							}).show();
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

/*	public synchronized void exitApp()
	{
		if (_myClient != null)
		{
			_myClient.closeConnection();
			_myClient = null;
		}
		if (_subscrRefs != null)
		{
			_subscrRefs = null;
		}
		if (_messageHandler != null)
		{
			_messageHandler = null;
		}
		this.finish();
		Process.sendSignal(Process.myPid(), Process.SIGNAL_QUIT);
	}
*/
	protected synchronized void genLauncher()
	{
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				getString(R.string.app_name));
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.addCategory(Intent.CATEGORY_LAUNCHER);

		intent2.setComponent(new ComponentName(this.getPackageName(),
				".activity.SplashActivity"));
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
				Intent.ShortcutIconResource.fromContext(this,
						R.drawable.icon));
		sendBroadcast(shortcutIntent);
	}

	/* @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, CREATE_LAUNCHER, 0,_menu_gen_launcher_res);
		MenuItem mItem = menu.findItem(CREATE_LAUNCHER);
		mItem.setIcon(R.drawable.back_down);
		menu.add(0, EXIT_APP,1,  _menu_exit_app_res);
		mItem = menu.findItem(EXIT_APP);
		mItem.setIcon(R.drawable.down_24_1);
		try {
			dissMissAllDialogIfExist();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case EXIT_APP:
				((ITDLApplication)getApplicationContext()).setExitApp(true);
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
			break; 
		}
		return super.onOptionsItemSelected(item);
	}*/

	@Override
	protected void onResume()
	{
		// TODO Auto-generated method stub
		super.onResume();
		
		showWelcomeMessage(loginResult);
		loginResult.Flush();
		
		//registerAppExitReceiver();
		
//		setTimeOnPage();
		if(isLightStreamerActivity(BaseActivity.this.getClass()))
		{
			INSTANCE_FOR_LIGHTSTREAMER_ONLY = this;
			connectLightStreamerExt(BaseActivity.this.getMyOwnContext());
		}
		
		_isInBackground = false;
		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
			return;
		}
		/*else {
			((ITDLApplication)getApplicationContext()).setCurrentActivityClass(BaseActivity.this.getClass());
		}*/

		if (!((ITDLApplication) getApplicationContext())
				.isLastSafelyExitApp())
		{
			unexpectedExitApplication();
			return;
		}

	/*	if (this.getParent() != null)
		{
			TDStockLog(TAG, String.format("current parent activity is %s", this
					.getParent().getClass().getSimpleName()));
		}
		else
		{
			TDStockLog(TAG, String.format(
					"%s lost its parent and ready to restore it!",
					BaseActivity.this.getClass().getSimpleName()));
			Intent forwardToMainActivity = new Intent(
					getApplicationContext(), RealtimeStockActivity.class);
			forwardToMainActivity
					.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
			startActivity(forwardToMainActivity);
		}*/

		if(this.getParent() != null)
		{
			_currActivityClass = this.getClass();
		}
	}

	@Override
	protected void onRestart()
	{
		// TODO Auto-generated method stub
		super.onRestart();
		_isInBackground = false;
		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
		/*else {
			((ITDLApplication)getApplicationContext()).setCurrentActivityClass(BaseActivity.this.getClass());
		}*/

	}

	@Override
	protected void onPause()
	{		
		_isInBackground = true;
		super.onPause();
		DetachedDisconnectMessage();		
		hideDisconnectMessage();		
		if (!SystemInfo.isNetworkingConnected(this))
		{
			return;
		}
		
		//unRegisterAppExitReceiver();

		closeSoftKeyboardIfNeed();   //add by haibo, 2011-07-25 to close softkeyboard on pause

		dissMissAllDialogIfExist();

		TDStockLog.d(TAG, BaseActivity.this.getClass().getSimpleName()
				+ " is in background( run in onPause)!");
		if (this.getParent() != null)
		{
			TDStockLog.d(TAG, String.format("current parent activity is %s", this
					.getParent().getClass().getSimpleName()));

//			_currentActivityClass = this.getClass();
//			_parentActivity = this.getParent();

		}
		else
		{
			TDStockLog.e(TAG, String.format("%s lost its parent!",
					BaseActivity.this.getClass().getSimpleName()));
		}

		if (_welcomeDialog != null)
		{
			_welcomeDialog.dismiss();
			_welcomeDialog = null;
		}		

	}
	
	//disconnect lightstreamer when home key pressed
	@Override
	protected void onUserLeaveHint()
	{
		TDStockLog.d(TAG,   "onUserLeaveHint!");
		super.onUserLeaveHint();
		//disconnectLightStreamer();
	}

	public static LS_Authentication_Result loginResult = new LS_Authentication_Result("", "", "", "");
	/** 顯示歡迎消息 */
     /* Higher version of Android provided new Screen when switching scale */
	protected CustomizeDialogDualMax _welcomeDialog = null;
	protected void showWelcomeMessage( final LS_Authentication_Result iLoginResult )
	{
		if(iLoginResult.errorMessage == null || (iLoginResult.errorMessage.length() == 0))
			return;
		
		if (_welcomeDialog == null)
		{
			_welcomeDialog = new CustomizeDialogDualMax( getMyOwnContext());
			_welcomeDialog.SetOnCancelFeature(true, null);
			_welcomeDialog.SetHeader("歡迎");			
		}
		_welcomeDialog.SetMsgContent(iLoginResult.errorMessage);			
		
		final String extraContent;

		extraContent = iLoginResult.linkContent;
		if ((extraContent != null) && (extraContent.length() != 0 ))
		{		
			IOnDialogButtonClick  _DownloadClick;

			_DownloadClick = new IOnDialogButtonClick()
			{
				@Override
				public void OnResponse()
				{
					Uri    uriObj;
					Intent intentObj;
					String linkContent;
					
					linkContent = extraContent;
					if ((linkContent == null) || (linkContent.length() == 0))
						return;
										
					intentObj = new Intent(Intent.ACTION_VIEW);
					uriObj = Uri.parse(linkContent);
					intentObj.setData(uriObj);
					startActivity(intentObj);
				}
			};
			_welcomeDialog.SetDualButton( iLoginResult.linkCaption, _DownloadClick, 
									 getString(R.string.ok), null);
		}
		else
			_welcomeDialog.SetSingleButton(getString(R.string.ok), null);
							
		_messageHandler.postDelayed(new Runnable()
		{
			public void run()
			{
				if (_welcomeDialog.isShowing() == false)
					_welcomeDialog.show();
			}
		}, 200);
	}
	
	public static void scrollToBottom(final View scroll, final View inner)
	{
		Handler mHandler = new Handler();

		mHandler.post(new Runnable()
		{
			public void run()
			{
				if (scroll == null || inner == null)
				{
					return;
				}

				View layout = (View) inner.getParent().getParent();

				//int offset = inner.getMeasuredHeight() - scroll.getHeight();
				int offset = layout.getMeasuredHeight()
						- scroll.getHeight();
				/*if (offset < 0) {
					offset =  0;
				}*/
				//	scroll.scrollTo(0, offset);
				//scroll.scrollTo(0, offset);  
				//inner.bringToFront();
				TDStockLog.d(TAG, " scroll.getTop()-> " + scroll.getTop());
				TDStockLog.d(TAG, " scroll.getHeight()-> " + scroll.getHeight());
				TDStockLog.d(TAG, " scroll.getMeasuredHeight()-> "
						+ scroll.getMeasuredHeight());
				TDStockLog.d(TAG, " scroll.getScrollY()-> " + scroll.getScrollY());

				if (offset > 0)
				{
					scroll.scrollTo(0, offset);
				}
				TDStockLog.d(TAG, "got its location! offset:" + offset);
			}
		});
	}

	public static void scrollToBottom(final View scroll, final int itemIndex,
			final int itemBlockHeight)
	{
		Handler mHandler = new Handler();

		mHandler.post(new Runnable()
		{
			public void run()
			{
				if (scroll == null)
				{
					return;
				}

				final int offset = (itemIndex) * itemBlockHeight;
				//	scroll.scrollTo(0, offset);
				scroll.scrollTo(0, offset);
				TDStockLog.d(TAG, "got its location! offset:" + offset);
			}
		});
	}

	//reset all variable that linked to the page
	public void resetPage()
	{
		_isShowingStreamerTimeoutLabel = false;
	}

	@Override
	protected void onDestroy()
	{
		TDStockLog.e(TAG, this.getClass().getSimpleName() + "is dead!");
		super.onDestroy();
	}

	/*
	 * show Customize Toast, There's three type: info, alert,error
	 */
	public static void showToast(Activity paramActivity, int paramInt,
			String paramString)
	{
		if (_toast == null)
			_toast = new Toast(paramActivity);
		_toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 150);

		View localView = paramActivity.getLayoutInflater().inflate(
				R.layout.richtoast, null);
		((TextView) localView.findViewById(R.id.dialog_content))
				.setText(paramString);
		ImageView localImageView = (ImageView) localView
				.findViewById(R.id.dialog_id);
		if (paramInt == 0)
			localImageView.setImageResource(R.drawable.dialog_default_icon);
		else if (paramInt == 1)
			localImageView.setImageResource(R.drawable.dialog_alert_icon);
		else
			localImageView.setImageResource(R.drawable.dialog_err_icon);
		_toast.setView(localView);
		_toast.setDuration(Toast.LENGTH_LONG);
		_toast.show();
	}

	protected Context getMyOwnContext()
	{
		return this.getParent() == null ?   getApplicationContext()  :  this.getParent() ; /*.getApplicationContext();*/
		//return getParent();
	}

//	public void initStreamerTimeoutLabel()
//	{
//		CommonDefn.DataMode dataMode = ((ITDLApplication) getApplicationContext())
//				.getDataMode();
//		String topic = dataMode == CommonDefn.DataMode.Realtime ? getResources()
//				.getString(R.string.cdr_tips)
//				: getResources().getString(R.string.light_reset_tips);
//		if (_streamerTimeoutLabel == null)
//		{
//			_streamerTimeoutLabel = (ViewGroup) LayoutInflater.from(this)
//					.inflate(R.layout.labeldialog, null);
//		}
//
//		((TextView) _streamerTimeoutLabel.findViewById(R.id.topic))
//				.setText(topic);
//
//		/*if(_streamerTimeoutLabel == null) {
//			_streamerTimeoutLabel = new RelativeLayout(this);
//			 ((RelativeLayout)_streamerTimeoutLabel).setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
//			  RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(140,  50);
//		  params.addRule( RelativeLayout.CENTER_HORIZONTAL);
//		  params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
//		  params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, 70);
//		TextView  label = new TextView(this);
//		label.setBackgroundColor(0xff0080ff);
//			label.setText(topic);
//			 ((RelativeLayout)_streamerTimeoutLabel).addView(label, params);
//		}*/
//
//		/*_streamerTimeoutLabel.setOnClickListener( new  OnClickListener(){
//			@Override
//			public void onClick(View v) {
//				//remove the icon appear in the activity
//			 		if(_streamerTimeoutLabel != null && mWindowManager != null) {
//			 			mWindowManager.removeViewImmediate(_streamerTimeoutLabel);
//			 			_streamerTimeoutLabel = null;
//			 		}
//				
//					   BaseActivity.this.resetPage();
//					   BaseActivity.this.connectLightStreamerEx();
//					   Log.d(TAG, "the clicking  works by using OnClick!");
//					   
//				  }
//			
//		});*/
//
//		/*_streamerTimeoutLabel.setOnTouchListener(  new OnTouchListener(){
//
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				performClickStreamerTimeoutLabel();
//				return false;
//			}
//			
//		});*/
//
//	}
//
//	public void showStreamerTimeoutLabel()
//	{
//		if (_isInBackground)
//		{
//			return; //haibo,  modified by haibo, 2011-06-09
//		}
//		try
//		{
//			//				if(mWindowManager == null) {
//			mWindowManager = (WindowManager) BaseActivity.this.getParent()
//					.getSystemService(Context.WINDOW_SERVICE);
//			//				}
//			Log.d(TAG, String.format(
//					"current context is %s in showStreamerTimeoutLabel ",
//					BaseActivity.this.getMyOwnContext().getClass()
//							.getSimpleName()));
//			mWindowParams = new WindowManager.LayoutParams();
//			mWindowParams.gravity = Gravity.BOTTOM
//					| Gravity.CENTER_HORIZONTAL;
//			mWindowParams.verticalMargin = StreamerTimeoutHandler.LOCATION_BOTTOM_OF_SCREEN_PERCENTAGE;
//			mWindowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
//			mWindowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
//
//			mWindowParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
//					| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
//			/*	| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON*/
//			/*	| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;*/
//			mWindowParams.format = PixelFormat.TRANSLUCENT;
//			mWindowParams.windowAnimations = 0;
//
//			mWindowManager.addView(_streamerTimeoutLabel, mWindowParams);
//			mWindowManager.updateViewLayout(_streamerTimeoutLabel,
//					mWindowParams);
//			_isShowingStreamerTimeoutLabel = true;
//		}
//		catch (Exception e)
//		{
//			Log.d(TAG, "can't show StreamerTimeoutLabel !");
//			e.printStackTrace();
//		}
//	}
//
//	public void dismissStreamerTimeoutLabel()
//	{
//		//remove the icon appear in the activity
//		/*if(mWindowManager == null) {
//			mWindowManager = (WindowManager)BaseActivity.this.getMyOwnContext().getSystemService(Context.WINDOW_SERVICE);
//			Log.e(TAG, "just constructor a new window manager! the elder  was  lost!");
//		}*/
//		if (_streamerTimeoutLabel != null && mWindowManager != null
//				&& _isShowingStreamerTimeoutLabel)
//		{
//			mWindowManager = (WindowManager) BaseActivity.this.getParent()
//					.getSystemService(Context.WINDOW_SERVICE);
//			Log
//					.d(
//							TAG,
//							String
//									.format(
//											"current context is %s in dismissStreamerTimeoutLabel ",
//											BaseActivity.this
//													.getMyOwnContext() != null ? BaseActivity.this
//													.getMyOwnContext()
//													.getClass()
//													.getSimpleName()
//													: "null"));
//			//mWindowManager.removeViewImmediate(_streamerTimeoutLabel);
//			mWindowManager.removeView(_streamerTimeoutLabel);
//			_streamerTimeoutLabel = null;
//			_isShowingStreamerTimeoutLabel = false;
//		}
//
//	}
//
//	public void performClickStreamerTimeoutLabel()
//	{
//		if (_streamerTimeoutLabel != null)
//		{
//			//remove the icon appear in the activity
//			/*if(_streamerTimeoutLabel != null && mWindowManager != null) {
//				mWindowManager.removeViewImmediate(_streamerTimeoutLabel);
//				_streamerTimeoutLabel = null;
//				_isShowingStreamerTimeoutLabel =  false;
//			}*/
//			dismissStreamerTimeoutLabel();
//
//			BaseActivity.this.resetPage();
//			BaseActivity.this
//					.connectLightStreamerExt(/*BaseActivity.this.getMyOwnContext()*/BaseActivity.this
//							.getParent());
//		}
//
//	}
//
//	public void onCdrPause()
//	{
//
//	}
//
//	public void onCdrResume()
//	{
//
//	}
//
//	public void onCdrCounterComeTo15Minutes()
//	{
//
//	}
//
//	@Override
//	public boolean dispatchTouchEvent(MotionEvent ev)
//	{
//
//
//		//			Log.d(TAG, String.format("current context is %s in dispatchTouchEvent ", BaseActivity.this.getMyOwnContext().getClass().getSimpleName()));
//
//		if ((!_isShowingStreamerTimeoutLabel)
//				|| (_streamerTimeoutLabel == null))
//		{
//			return super.dispatchTouchEvent(ev);
//		}
//
//		Rect hitRect = new Rect();
//		_streamerTimeoutLabel.getHitRect(hitRect);
//		int x = (int) ev.getX();
//		int y = (int) ev.getY();
//		Log.d(TAG, String.format("label size(width,height)=(%d,%d) ",
//				_streamerTimeoutLabel.getWidth(), _streamerTimeoutLabel
//						.getHeight()));
//		Log.d(TAG, "touch x: " + x + ",touch y:" + y);
//		Log.d(TAG, String.format(
//				"dest rect: left, right, top, bottom: %d,%d,%d,%d",
//				hitRect.left, hitRect.right, hitRect.top, hitRect.bottom));
//
//		int minX = (_display.getWidth() - _streamerTimeoutLabel.getWidth()) / 2;
//		int maxX = minX + _streamerTimeoutLabel.getWidth();
//		//			int  minY = _streamerTimeoutLabel.getHeight() -80;
//		int minY = _streamerTimeoutLabel.getHeight()
//				- _display.getHeight()
//				* StreamerTimeoutHandler.LOCATION_BOTTOM_OF_SCREEN_PERCENTAGE
//				/ 100;
//		int maxY = _streamerTimeoutLabel.getHeight();
//		Log.d(TAG, String.format(
//				"dest range: minX, maxX, minY, maxY: %d,%d,%d,%d", minX,
//				maxX, minY, maxY));
//		//			if(hitRect != null && hitRect.contains(x, y)) {
//		if ((x >= minX && x <= maxX) && (y >= minY && y <= maxY))
//		{
//			
//
//			dismissStreamerTimeoutLabel();
//
//			BaseActivity.this.resetPage();
//			BaseActivity.this
//					.connectLightStreamerExt(/*BaseActivity.this.getMyOwnContext()*/BaseActivity.this
//							.getParent());
//			Log.d(TAG, "the clicking  works by using onTouchEvent!");
//			return true;
//		}
//		return super.dispatchTouchEvent(ev);
//	}

	private void dissMissAllDialogIfExist()
	{
		if (_retryDialog != null && _retryDialog.isShowing())
		{
			_retryDialog.dismiss();
		}
		//			  if(_progressDialog != null && _progressDialog.isShowing()) {
		//				  _progressDialog.dismiss();
		//			  }
	}

	protected void startAdAnim()
	{
		TDStockLog.d(TAG, "enter startAdAnim");
		final int[] ad_ids = { R.drawable.ad_a, R.drawable.ad_b,
				R.drawable.ad_c, R.drawable.ad_d };

		if (_prefs != null)
		{
			//get the present ad;
			int currentAdResourcesId = _prefs.getInt(
					CommonDefn.PREFERENCE_PRESENT_AD_ID, R.drawable.ad_a);
			TDStockLog.d(TAG, "current ad id:  " + currentAdResourcesId);

			final View importPanel = ((ViewStub) findViewById(R.id.stub_import))
					.inflate();
			if (importPanel != null)
			{
				try
				{
					importPanel.setVisibility(View.VISIBLE);
					final Animation anim = AnimationUtils.loadAnimation(
							this, R.anim.ad_animation);
					ImageView ad = (ImageView) importPanel
							.findViewById(R.id.image_ad);
					ad.setImageResource(currentAdResourcesId);

					anim
							.setAnimationListener(new Animation.AnimationListener()
							{

								@Override
								public void onAnimationStart(
										Animation animation)
								{
									// TODO Auto-generated method stub
									TDStockLog.d(TAG, "start  anim");
								}

								@Override
								public void onAnimationRepeat(
										Animation animation)
								{
									// TODO Auto-generated method stub

								}

								@Override
								public void onAnimationEnd(
										Animation animation)
								{
									// TODO Auto-generated method stub
									importPanel
											.setVisibility(View.INVISIBLE);
									TDStockLog.d(TAG, "ad anim is stopped");
								}
							});

					ad.startAnimation(anim);
				}
				catch (Exception e)
				{
					TDStockLog.d(TAG, "can't load ad!");
				}

			}

			//set the next present id;

			int adTotal = ad_ids.length;
			int adIndex = 0;
			for (adIndex = 0; adIndex < adTotal; adIndex++)
			{
				if (currentAdResourcesId == ad_ids[adIndex])
				{
					break;
				}
			}

			_prefs.edit().putInt(
					CommonDefn.PREFERENCE_PRESENT_AD_ID,
					adIndex == ad_ids.length - 1 ? ad_ids[0]
							: ad_ids[adIndex + 1]).commit();
			//set the next present id;

		}

	}

	/*protected void unSubscribeItems()
	{
		try
		{

			_myClient = ((ITDLApplication) getApplicationContext())
					.getLightStreamerClient();
			SubscribedTableKey[] subscrKeys = new SubscribedTableKey[_subscrRefs
					.size()];
			int index = 0;
			for (SubscribedTableKey value : _subscrRefs)
			{
				subscrKeys[index++] = value;
			}
			//SubscribedTableKey[] subscrKeys = (SubscribedTableKey[]) _subscrRefs.toArray(new SubscribedTableKey[0]);
			_myClient.unsubscribeTables(subscrKeys);
			_subscrRefs.clear();
			Log.d(TAG, "unsubscribeTables all items!");
		}
		
		catch (Exception e)
		{
			Log.d(TAG, "unsubscribe exception happened!"
					+ (e.getMessage() == null ? "" : e.getMessage()));
			e.printStackTrace();
			
			//retry once;
			if(((ITDLApplication) getApplicationContext()).isLightStreamerConnected())
			{
				SubscribedTableKey[] subscrKeys = new SubscribedTableKey[_subscrRefs
				                                					.size()];
				                                			int index = 0;
				                                			for (SubscribedTableKey value : _subscrRefs)
				                                			{
				                                				subscrKeys[index++] = value;
				                                			}
				                                			//SubscribedTableKey[] subscrKeys = (SubscribedTableKey[]) _subscrRefs.toArray(new SubscribedTableKey[0]);
				                                			try
													{
														_myClient.unsubscribeTables(subscrKeys);
														_subscrRefs.clear();
													}
													catch (Exception e1)
													{
														((ITDLApplication) getApplicationContext()).setLightStreamerConnected(false);
														_myClient.closeConnection();
														Log.d(TAG, "unsubscribe exception happened in retry!"
																+ (e.getMessage() == null ? "" : e.getMessage() + " in retry !"));
														e1.printStackTrace();
													}
													
			}
			

		}
	}*/

/*	protected class UnSubscribeItemsTask extends AsyncTask<String, Void, Void>
	{

		@Override
		protected Void doInBackground(String... params)
		{
			unSubscribeItems();
			return null;
		}

		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);

		}

	}*/

	/*protected void unSubscribeAllItems()
	{
		
	  if (!((ITDLApplication) getApplicationContext()).isExitApp())
		new UnSubscribeItemsTask().execute(); //modified by haibo, 2011-06-14, to avoid anr
	}
	
	
	
	protected  void addSessionListenerToLightStreamer() {
		_myClient = ((ITDLApplication) getApplicationContext())
		.getLightStreamerClient();
		
		try
		{
			subscribeItems(_myClient,
					new String[] {   "session" + ((ITDLApplication) BaseActivity.this.getApplicationContext()).getSessionToken()},
					new String[] { "ForceDisconnect" },"TELETEXT",
					new CallbackHandlerOnSession());
			Log.e(TAG, String.format("subscribe session : %s successfully!",  ((ITDLApplication) BaseActivity.this.getApplicationContext()).getSessionToken()) );
		}
		catch (Exception e)
		{
			Log.e(TAG, e.getMessage()==null? " unkown exception ahppened in addSessionListenerToLightStreamer!" : e.getMessage());
			e.printStackTrace();
		}
		
		
	}*/
	
	
	
	
	
	/*
	private class CallbackHandlerOnSession implements
	LightStreamerHandlerInterface
    {
	public void onUpdate(int itemPos, String itemName, UpdateInfo update)
	{
		
		Log.d(TAG, "need to ForceDisconnect: " + update.getNewValue("ForceDisconnect"));
		try
		{
			if(update.getNewValue("ForceDisconnect").equalsIgnoreCase("true")) {
				
				_myClient = ((ITDLApplication) getApplicationContext())
				.getLightStreamerClient();
				_myClient.closeConnection();
				
				
				handleAnotherLogonAppear();
				
				return;
			}
		}
		catch (Exception e)
		{
			Log.e(TAG, e.getMessage()==null? " unkown exception ahppened in CallbackHandlerOnSession!" : e.getMessage());
			e.printStackTrace();
		}
		
	}
};
*/

	
	
	
	@Override
	protected void onNewIntent(Intent intent)
	{
		TDStockLog.d(TAG, "restore task for : " + BaseActivity.this.getClass().getSimpleName());
		super.onNewIntent(intent);
		TDStockLog.d(TAG, "onNewIntent");
	}

	protected void  handleAnotherLogonAppear() {
		
		AccountLoginActivity._isAnotherLogonClientAppear = true;   //notify the activity there's another logon.
		/*((ITDLApplication) getApplicationContext())
		.getLightStreamerClientForNew();*/
		
		
		Intent forwardToLogonActivity = new Intent(this.getApplicationContext(), AccountLoginActivity.class);
		forwardToLogonActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK| Intent.FLAG_ACTIVITY_NO_USER_ACTION);
		/*startActivity(forwardToLogonActivity);*/
		SwitchActivityFromHost (AccountLoginActivity.class, forwardToLogonActivity);
		//this.startActivity(forwardToLogonActivity);
	}
	
	protected void  closeSoftKeyboardIfNeed()
	{
		View focused  =  this.getCurrentFocus();
		if(focused != null)
		{
			Object service = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if(service != null)
			{
				InputMethodManager imm = (InputMethodManager) service;
				imm.hideSoftInputFromWindow(focused.getWindowToken(), 0); // close the soft if need
			}
		}	
	}

//	private void setTimeOnPage()
//	{
//		if(BaseActivity.this.getClass().getSimpleName().equals(CurrentStockInfoActivity.class.getSimpleName()) 
//			||  BaseActivity.this.getClass().getSimpleName().equals(PortfolioActivity.class.getSimpleName()) ) 
//		{
//			TDStockLog.d(TAG, "is entering stock or monitor page !");
//			((ITDLApplication) getApplicationContext()).setPageEnterTimer(System.currentTimeMillis());
//		}
//		else {
//			TDStockLog.d(TAG, "leaved  the stock / monitor page already !");
//			if(((ITDLApplication) getApplicationContext()).getPageLeaveTime() == 0l)
//				((ITDLApplication) getApplicationContext()).setPageLeaveTime(System.currentTimeMillis());
//			//don't change the  leave cdr time if the user switch between  non-cdr page
//		}
//		
//		
//	}



/* This can not be null, if some other activity forget to set this, there will be error on running */
//	@Override
//	protected ActivityGroupController GetActivityGroupController() {
//		return null;
//	}
//	
	
	
	/**
	 * 
	 *  connect(reconnect) to lightstreamer server
	 *
	 */
	private  boolean   isGetSession   = false;
	private class ConnectLightStreamerEx extends BaseAsyncTask
	{
		
		private final static int  SESSION_WAIT_TIME_MS = 5000 * 3 * 4; //by zor 2011-12-06
		private final static int CONNECTION_WAIT_TIME_MS = 10000 * 3 * 2; //by zor 2011-12-06
		
		private final int			RETRY_TOTAL		= 1;						//only  allowed to retry once
		private ConditionVariable	conditionVariableForRequestSession;								/* =  new ConditionVariable();*/
		private int				retry_times		= 0;
//		private boolean   			isGetSession        = false;
		
		public ConnectLightStreamerEx(Context context)
		{
			super(context);
			isGetSession = false;
		}
		
		@Override
		protected Void doInBackground(String... params)
		{			
			TDStockLog.d(TAG, "cameFromTag=DUG_CONN=doInBackground.... isGetSession="+isGetSession);
			if(appHost.LSClient_IsConnected())
			{
				isGetSession = true;
				return null;
			}

			conditionVariableForRequestSession = new ConditionVariable();
			conditionVariableForConnection =  new ConditionVariable();
			isGetSession = false;
			if (((ITDLApplication) getApplicationContext()).isAuthComeFromActivationCode()) 
			{
				String activationCode = getActivationCode();
				appHost.LS_RequestFreeTrialActivate(activationCode,  new ILS_UserClient_Authentication_Report() {

					@Override
					public void LS_UserClient_Authentication_Response(
							LS_UserClient_Authentication_Result iResponse) {
						conditionVariableForRequestSession.open();
						if (iResponse == null)
						{
							return;
						}

						if (iResponse.successfulSend == false)
						{
							return;
						}

						loginResult = new LS_Authentication_Result(iResponse);						
						if (iResponse.statusCode.equals("0"))
						{
							((ITDLApplication) getApplicationContext())
							.setSessionAccount(appHost.GetLSClient_AccountLogonName());
							((ITDLApplication) getApplicationContext())
							.setSessionToken(appHost.GetLSClient_SessionKey());
							isGetSession =  true;
							TDStockLog.d(TAG, "got the session!");
						}
						return;
						
					}
					
				});  //do in background...
				
				TDStockLog.d(TAG, "ready to login!");
				conditionVariableForRequestSession.block(SESSION_WAIT_TIME_MS);
				
				if(!isGetSession)
				{
					TDStockLog.d(TAG, " fail to get the session!");
					return null;
				}
			}
			else
			{
				appHost.LSClient_Logon(getUser(), getPwd(), /*_prefs.getString(CommonDefn.PREFERENCE_DEVICE_ID, ""),*/  new ILS_UserClient_Authentication_Report()
				{
					@Override
					public void LS_UserClient_Authentication_Response(
							LS_UserClient_Authentication_Result iResponse) {
						conditionVariableForRequestSession.open();
						if (iResponse == null)
						{
							return;
						}

						if (iResponse.successfulSend == false)
						{
							return;
						}

						loginResult = new LS_Authentication_Result(iResponse);						
						if (iResponse.statusCode.equals("0"))
						{
							
							TDStockLog.d(TAG, "got the session!");
							((ITDLApplication) getApplicationContext())
							.setSessionAccount(appHost.GetLSClient_AccountLogonName());
							((ITDLApplication) getApplicationContext())
							.setSessionToken(appHost.GetLSClient_SessionKey());
	
							isGetSession =  true;
						}
						return;
						
					}
					
				});  //do in background...
				TDStockLog.d(TAG, "cameFromTag=ready to login!");
				conditionVariableForRequestSession.block(SESSION_WAIT_TIME_MS);				
				if(!isGetSession)
				{
					TDStockLog.d(TAG, " fail to get the session!");
					return null;
				}
				
				
			}
			
			 TDStockLog.d(TAG, "ready to connect!");
			// Andy Not Necessay, since it is an auto detect process
			//appHost.LSClient_Connect();
			
			 conditionVariableForConnection.block(CONNECTION_WAIT_TIME_MS);
			 

			return null;
		}
		
		
		@Override
		protected void onCancelled()
		{
			super.onCancelled();
			TDStockLog.d(TAG, "cameFromTag=DUG_CONN=onCancelled..."+isGetSession);
		}

		// can use UI thread here
		@Override
		protected void onPostExecute(Void result)
		{
			super.onPostExecute(result);
			
			if(!isGetSession ||  ! appHost.LSClient_IsConnected()) {
				retry();
				 return;
			}
			
			try
			{
				//addSessionListenerToLightStreamer();  //added by haibo, 2011-07-21
				startupLightStreamerTimeoutThread();
				BaseActivity.this.onConnectionEstablished();
				showWelcomeMessage(loginResult);  //the message coming from the logon in delay mode
				loginResult.Flush();
			}
			catch (Exception e)
			{
				TDStockLog.e(TAG, e.getMessage() == null ? "unknown exception appeared!" : e.getMessage()) ;
				retry();
			}
		}
	}
	
	@Override
	public void LS_UserClient_ConnectionReport(final CONNECTION_STATUS iStatus)
	{
		
		TDStockLog.d(TAG, "cameFromTag=DUG_CONN=" + iStatus.name()  );
//		CONNECTION_STATUS.CONNECTED
		
		if(iStatus == CONNECTION_STATUS.CLOSE_BY_FORCE )
		{
			handleAnotherLogonAppear();
			return;
		}
		
		if( conditionVariableForConnection != null )
			conditionVariableForConnection.open();
		
		if(iStatus == CONNECTION_STATUS.CONNECTED)
		{			
			isGetSession = true;			
			if(!appHost.LSClient_IsConnected())
			{
				TDStockLog.e(TAG, "the framework  has some issue on connection status");
			}
			
			BaseAsyncTask.cancelAllTask();
			startupLightStreamerTimeoutThread();
			onConnectionEstablished();
			showWelcomeMessage(loginResult);
			loginResult.Flush();
			
			TDStockLog.d(TAG, appHost.GetLSClient_SessionKey());
			
			((ITDLApplication) getApplicationContext()).setSessionAccount(appHost.GetLSClient_AccountLogonName());
			((ITDLApplication) getApplicationContext()).setSessionToken(appHost.GetLSClient_SessionKey());			
			hideDisconnectMessage();
		}
		else
		{
			if(!_isInBackground)
			{
				 showDisconnectMessage();
			}
			
		}
		
		
	/*	if(iStatus == CONNECTION_STATUS.CLOSE_BY_CONNECTION_DROP ||   iStatus == CONNECTION_STATUS.CONNECTION_FAIL ||  iStatus == CONNECTION_STATUS.  NOT_REQUEST) {
			 if (!this._isInBackground)  
			 {
				 retry();
			 }
				 	
		}
		else if (iStatus == CONNECTION_STATUS.CONNECTED ) {
			if (_retryDialog != null)
			{
				_retryDialog.dismiss();
				_retryDialog = null;
			}
		}*/
		

	}



	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, CREATE_LAUNCHER, 0, _menu_gen_launcher_res);
		MenuItem mItem = menu.findItem(CREATE_LAUNCHER);
		mItem.setIcon(R.drawable.back_down);
		menu.add(0, EXIT_APP, 1, _menu_exit_app_res);
		mItem = menu.findItem(EXIT_APP);
		mItem.setIcon(R.drawable.down_24_1);
		
		try
		{
			CustomizeDialog.dismissAll();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext())
						.setExitApp(false);  //modified by haibo in 2012-03-29 
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int iFeature, MenuItem iItem)
	{
		switch (iItem.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext())
						.setExitApp(false);  ////modified by haibo in 2012-03-29 
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return true;
	}	
	
	protected synchronized void exitApp()
	{	
/* Andy */		
//	    CdrSender sender = ((ITDLApplication) getApplicationContext()).getCdrSender();
//		if(sender != null) {
//			sender.sendCdrInfo();
//		}
		
		
	/*	try
		{
			appHost.LSClient_Disconnect();
			CustomizeDialog.dismissAll();
			//disconnectLightStreamer();
			 
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		this.finish();
		Process.sendSignal(Process.myPid(), Process.SIGNAL_QUIT);*/
		
		appHost.LSClient_Disconnect();
		CustomizeDialog.dismissAll();
		
		Intent goToHomeScreen = new Intent(Intent.ACTION_MAIN);
		goToHomeScreen.addCategory(Intent.CATEGORY_HOME);
		goToHomeScreen.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |  Intent.FLAG_ACTIVITY_NEW_TASK);
		getApplicationContext().startActivity(goToHomeScreen);   //it seems to press home key
		

		
		
	}
	
	
	
	private  void retry()
	{

		if (_retryDialog != null)
		{
			_retryDialog.dismiss();
			_retryDialog = null;
		}

		if (!((ITDLApplication) getApplicationContext())
				.isLastSafelyExitApp())
		{
			return; //if the activity is restart by android  itself,  no need  to retry;
		}

		if (BaseActivity.this.getParent() == null)
		{
			return; //if it is not in tab host, no need to retry  to avoid non-stop-looper;
		}

		if (_retryDialog == null)
		{
			_retryDialog = new CustomizeDialog(
					/*BaseActivity.this.getMyOwnContext()*/BaseActivity.this
							.getParent(), getResources().getString(
							R.string.info),
					getResources().getString(
							R.string.light_streamer_error))
			{
				@Override
				public void onClick(View v)
				{
					/** When OK Button is clicked, dismiss the dialog */
					if (v == okButton)
					{
						dismiss();
						appHost.LSClient_Disconnect();
						new ConnectLightStreamerEx(
								/*BaseActivity.this.getMyOwnContext()*/BaseActivity.this
										.getParent())
								.execute("retry");
						//  Thread.yield();
						TDStockLog.d(TAG, " retry!");
					}

				}
			};
			_retryDialog.setCancelable(true);
		}

		if (!_isInBackground)
		{
			_retryDialog.show();
		}

	}
	
	
	
	protected  String  getAppVersion () 
	{
			String result = " 1.0.0";
			
			try {
				result = getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return result;
		
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if(id == _id_Networking_Disconnected_Tips)
			return  new CustomizeDialog(getMyOwnContext(), getString(R.string.info), getString(R.string.networking_disconnect_tips));
		else
			return null;
	}
	
	
	
	protected  boolean showNoNetworkTips(int... args) {
		
		boolean result = false;
		if(args.length < 1) {
			
			if (!SystemInfo.isNetworkingConnected(this))
			{
				result = true;
				//this.oncr
				///new CustomizeDialog(getMyOwnContext(), getString(R.string.info), getString(R.string.networking_disconnect_tips)).show();
				
				
				
			getParent().runOnUiThread(new Runnable()
				{
					public void run()
					{ 
						//showDialog(_id_Networking_Disconnected_Tips);
						showToast(getParent(), 1, getString(R.string.networking_disconnect_tips));
					}
				});
				
				
			}
			
		}
		else {
			getParent().runOnUiThread(new Runnable()
			{
				public void run()
				{ 
					//showDialog(_id_Networking_Disconnected_Tips);
					showToast(getParent(), 1, getString(R.string.networking_disconnect_tips));
				}
			});
		}
		
		return result;
	}


	//update by max 2011-10-10
	/*
	 * 跳到足球界面
	 */
//	protected void forwardToSoccerActivity()
//	{
//		TDStockLog.d(TAG, "forwardToSoccerActivity");
//		if(!((ITDLApplication) getApplicationContext()).getIsSoccer())
//		{
//			new CustomizeDialog(this.getParent(), "", appHost.GetLSClient_SportMessag().equals("")?getResources().getString(R.string.realtime_info_msg):appHost.GetLSClient_SportMessag(), getResources().getString(R.string.ok)).show();
//		}
//		else
//		{
//			Intent it = new Intent(this, MainTabActivity.class);
//			it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			SwitchActivityFromHost(MainTabActivity.class, it);
//		}
//	}

	//by ouyangzhihui 2011-09-22
	/*
	 * 跳到赛马界面
	 */
//	protected void forwardToHorseraceActivity()
//	{
//		TDStockLog.d(TAG, "forwardToHorseraceActivity");
//		if(!((ITDLApplication) getApplicationContext()).getIsHorse())
//		{
//			new CustomizeDialog(this.getParent(), "", appHost.GetLSClient_HorseMessage().equals("")?getResources().getString(R.string.realtime_info_msg):appHost.GetLSClient_HorseMessage(), getResources().getString(R.string.ok)).show();
//		}
//		else
//		{
//			Intent it = new Intent(this, cc.telecomdigital.tdstock.horserace.activity.MainActivity.class);
//			it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//			SwitchActivityFromHost(cc.telecomdigital.tdstock.horserace.activity.MainActivity.class, it);
//		}
//	}
	
	
	
	//add visibility for children
	public void SwitchForwardActivity(
			Class<? extends Activity> iActivityClass, Intent iIntentObj)
	{
		super.SwitchForwardActivity(iActivityClass, iIntentObj);
	}
	
	
	
	protected PopupWindow lsStatusPopupView = null;
	protected View        viewObj = null;
	protected Runnable popupWindow_runnable = null;	
	protected void AttachDisconnectMessage()
	{
		
		if (lsStatusPopupView == null)
		{
			LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			viewObj  = inflatObj.inflate(R.layout.prompt_msgbox, null);
			
			CommonDefn.DataMode dataMode = ((ITDLApplication) getApplicationContext())
			.getDataMode();
			String topic = dataMode == CommonDefn.DataMode.Realtime ? getResources()
			.getString(R.string.cdr_tips)
			: getResources().getString(R.string.light_reset_tips);
			
			((TextView)viewObj.findViewById(R.id.prompt_msgboxContent)).setText(topic);
			viewObj.findViewById(R.id.prompt_msgboxContent).setOnClickListener( new OnClickListener()
			{
				@Override
				public void onClick(View arg0)
				{
					performClickStreamerTimeoutLabel();
				}
	
			});
			lsStatusPopupView = new PopupWindow(viewObj, 
					 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);			
			lsStatusPopupView.setAnimationStyle(R.anim.zoom_enter);
			lsStatusPopupView.setOutsideTouchable(true);			
		}
		
		if (!lsStatusPopupView.isShowing())
		{
			if (popupWindow_runnable == null)
			{
				popupWindow_runnable = new Runnable()
				{
					public void run()
					{
						lsStatusPopupView.showAtLocation(viewObj, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 40);
						_isShowingStreamerTimeoutLabel = true;
					};
				};
			}
			if(_messageHandler ==  null) {
				_messageHandler = new Handler();
			}
			_messageHandler.postDelayed(popupWindow_runnable, 300);				
		}			
	}		
	
	protected void DetachedDisconnectMessage()
	{
		_isShowingStreamerTimeoutLabel = false;
		if (lsStatusPopupView == null)
			return;
		
		if (popupWindow_runnable != null)
			_messageHandler.removeCallbacks(popupWindow_runnable);
		
		if (lsStatusPopupView.isShowing())
			lsStatusPopupView.dismiss();
	}
	
	
	protected void performClickStreamerTimeoutLabel()
	{
		if (LS_ResumeAllItem()== true)
			DetachedDisconnectMessage();
	}
	 
	 
	protected PopupWindow  netStatusPopupView = null;
	protected View        netViewObj = null;
	protected Runnable  netPopupWindow_runnable = null;	
	protected void  showDisconnectMessage()
	{			
			if (netStatusPopupView == null)
			{
				LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				
				netViewObj  = inflatObj.inflate(R.layout.prompt_network_disconn_pop, null);
				
				/*CommonDefn.DataMode dataMode = ((ITDLApplication) getApplicationContext())
				.getDataMode();*/
				/*String topic = dataMode == CommonDefn.DataMode.Realtime ? getResources()
				.getString(R.string.cdr_tips)
				: getResources().getString(R.string.light_reset_tips);
				
				((TextView)netViewObj.findViewById(R.id.prompt_networking_discon_tips)).setText(topic);*/
				netViewObj.findViewById(R.id.prompt_networking_discon_tips).setOnClickListener( new OnClickListener()
				{
					@Override
					public void onClick(View arg0)
					{
						if (LS_ResumeAllItem()== true)
							hideDisconnectMessage();
					}
		
				});
				netStatusPopupView = new PopupWindow(netViewObj, 
						 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);			
				netStatusPopupView.setAnimationStyle(R.anim.zoom_enter);
				netStatusPopupView.setOutsideTouchable(true);			
			}
			
			if (!netStatusPopupView.isShowing())
			{
				if (netPopupWindow_runnable == null)
				{
					netPopupWindow_runnable = new Runnable()
					{
						public void run()
						{
							netStatusPopupView.showAtLocation(netViewObj, Gravity.BOTTOM|Gravity.RIGHT, 0, 45);
						//	_isShowingStreamerTimeoutLabel = true;
						};
					};
				}
				if(_messageHandler ==  null) {
					_messageHandler = new Handler();
				}
				_messageHandler.postDelayed(netPopupWindow_runnable, 300);				
			}			
	}		
		
	protected void hideDisconnectMessage()
	{
			if(_messageHandler ==  null) {
				_messageHandler = new Handler();
			}
			//_isShowingStreamerTimeoutLabel = false;
			if (netStatusPopupView == null)
				return;
			
			if (netPopupWindow_runnable != null)
				_messageHandler.removeCallbacks(netPopupWindow_runnable);
			
			if ((netStatusPopupView != null) && netStatusPopupView.isShowing())
				netStatusPopupView.dismiss();
	}
		
		protected final static int             LIGHTSTREAMER_TIMEOUT_MS = 1000 * 15 * 2 * 2;   //15 seconds;   //by zor 2011-12-06
		protected Timer lightStreamerTimeoutThread;
		
		protected  void startupLightStreamerTimeoutThread()
		{
			if (isLightStreamerActivity(getClass()) == false)
			{
				if (debugMode)
					TDStockLog.i(GetIdentity(), "No LightStreamer Subscription on this Activity");
				return;
			}
			
			if (debugMode)
				TDStockLog.i(GetIdentity(), "Will Start LightStreamer Item Timer");			
			
			if(lightStreamerTimeoutThread == null)
			{
				lightStreamerTimeoutThread = new Timer();
			}
			
			final TimerTask showMessageJob = new TimerTask()
			{
				public void run()
				{
					if (appHost.LSClient_IsConnected() == false)
						return;
					_messageHandler.postDelayed( new Runnable()
					{
						public void run()
						{
							if(!BaseActivity.this._isInBackground)
							{
								showDisconnectMessage();
							}
							
						}
					}, 100);	
				}
			};
			
			lightStreamerTimeoutThread.schedule(showMessageJob, LIGHTSTREAMER_TIMEOUT_MS);
			
		}
		
	protected void killLightStreamerTimeoutThread(){
			if(lightStreamerTimeoutThread  != null) {
				lightStreamerTimeoutThread.cancel();
			}
			lightStreamerTimeoutThread = null;
			hideDisconnectMessage();
		}
	
	
	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{
			killLightStreamerTimeoutThread();
	}
	
	@Override
	public void ReporterTicker_Response(int iRemainSecond)
	{
		if(debugMode)
			TDStockLog.i(GetIdentity(), "RemainSecond = " + iRemainSecond);
		
		if(isLightStreamerActivity(BaseActivity.this.getClass() ) || BaseActivity.this.getClass().equals(PortfolioActivity.class) )
		{
			if (iRemainSecond == 0)
				AttachDisconnectMessage();		
		}
			
	/*	else
			DetachedDisconnectMessage();*/
	}
	

}
